#!/bin/sh
# Copyright (c) 2012, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2012-03-11

job_init() {
 TMP="/tmp/`basename $0`.$hostname.$$.tmp"
 mkdir "$TMP" ||exit 1
 JOBCNT=0
 JOBPIDS=""
 PARENTPID=$$
}

fork_job() {
 $@ >> "$TMP"/$JOBCNT.$PARENTPID.tmp.txt 2>&1 &
 JOBPIDS="$JOBPIDS $!"
 JOBCNT=`expr 0$JOBCNT + 1`
}

join_jobs() {
 if [ -z "$JOBPIDS" ] ; then
  rmdir "$TMP"
  exit 1
 fi
 TIMEOUT=${1-1}
 [ -n "$TMP" ] || exit 1
 [ "$TMP" != "/" ] || exit 1
 echo "info: join_jobs waiting for timeout"
 sleep $TIMEOUT
 local I=0
 for JOBPID in $JOBPIDS ; do
  if
   kill $JOBPID 2>/dev/null
  then
   echo "error: killed $JOBPID by timeout" >> $TMP/$I.$$.tmp.txt
  fi
  I=`expr $I + 1`
 done
 echo "info: join_jobs waiting for 9"
 sleep 0.5
 kill -9 $JOBPIDS 2>/dev/null
 echo "info: join_jobs find"
 find "$TMP" -type f -iname "*.tmp.txt" |
 sed "s~^$TMP/*~~" |
 sort -n |
 while read OUT ; do
  cat "$TMP/$OUT"
  rm "$TMP/$OUT"
 done
 rmdir "$TMP"
}
